# -*- coding: utf-8 -*-

from osv import fields,osv
from osv.orm import browse_record
import tools
from functools import partial
import pytz
import pooler
from tools.translate import _
from service import security
import netsvc

class aas_result_by_semester(osv.TransientModel):
    _name = 'aas.result.by.semester'
    _columns = {
        'semester': fields.char('Học kỳ', size=64),
        'gpa': fields.float('Điểm trung bình', digits=(16,2)),
    }
    _defaults = {}
    def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
        sql = ''' DELETE FROM aas_result_by_semester '''
        cr.execute(sql)

        user_obj = self.pool.get('res.users')
        year_obj = self.pool.get('aas.academic.year')
        semester_obj = self.pool.get('aas.academic.semester')
        
        data_to_create = []
        
        study_results = user_obj.get_study_result(cr, uid, uid, context=context)
        ids = year_obj.search(cr, uid, [('name', 'in', study_results['details'].keys())], context=context)
        ordered_years = []
        if ids:
            for year in year_obj.browse(cr, uid, ids, context=context):
                ordered_years.append([year.id, year.name])
            for year_id, year_name in ordered_years:
                ordered_semesters = []
                sem_ids = semester_obj.search(cr, uid, [('academic_year', '=', year_id)], context=context)
                for semester in semester_obj.browse(cr, uid, sem_ids, context=context):
                    ordered_semesters.append([semester.id, semester.name])
                for sem_id, sem_name in ordered_semesters:
                    if study_results['details'][year_name].has_key(sem_name):
                        lines = study_results['details'][year_name][sem_name]
                        avg_mark = 0.00
                        sum_mark = 0.00
                        total_credit = 0
                        for line in lines:
                            total_credit += line[6]
                            sum_mark += (line[7] * line[6])
                        if total_credit > 0:
                            avg_mark = round(float(sum_mark) / float(total_credit), 2)
                        data_to_create.append({'semester': '(' + year_name + ') ' + sem_name, 'gpa': avg_mark})
        ids = []
        if data_to_create:
            for data in data_to_create:
                id = self.create(cr, uid, data, context=context)
                ids.append(id)
        return ids
aas_result_by_semester()

class aas_result_by_year(osv.TransientModel):
    _name = 'aas.result.by.year'
    _columns = {
        'year': fields.char('Năm học', size=64),
        'gpa': fields.float('Điểm trung bình', digits=(16,2)),
    }
    _defaults = {}
    def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
        sql = ''' DELETE FROM aas_result_by_year '''
        cr.execute(sql)

        user_obj = self.pool.get('res.users')
        year_obj = self.pool.get('aas.academic.year')
        
        data_to_create = []
        
        study_results = user_obj.get_study_result(cr, uid, uid, context=context)
        ids = year_obj.search(cr, uid, [('name', 'in', study_results['details'].keys())], context=context)
        ordered_years = []
        if ids:
            for year in year_obj.browse(cr, uid, ids, context=context):
                ordered_years.append([year.id, year.name])
            for year_id, year_name in ordered_years:
                avg_mark = 0.00
                sum_mark = 0.00
                total_credit = 0
                for sem_name in study_results['details'][year_name].keys():
                    lines = study_results['details'][year_name][sem_name]
                    for line in lines:
                        total_credit += line[6]
                        sum_mark += (line[7] * line[6])
                if total_credit > 0:
                    avg_mark = round(float(sum_mark) / float(total_credit), 2)
                data_to_create.append({'year': year_name, 'gpa': avg_mark})
        ids = []
        if data_to_create:
            for data in data_to_create:
                id = self.create(cr, uid, data, context=context)
                ids.append(id)
        return ids
aas_result_by_year()


class aas_result_distribution(osv.TransientModel):
    _name = 'aas.result.distribution'
    _columns = {
        'key': fields.char('Xếp loại', size=64),
        'value': fields.integer('Số lượng'),
    }
    _defaults = {}
    def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
        sql = ''' DELETE FROM aas_result_distribution '''
        cr.execute(sql)

        user_obj = self.pool.get('res.users')
        year_obj = self.pool.get('aas.academic.year')
        c_obj = self.pool.get('aas.classification')
        
        khoang = []
        all_c = c_obj.search(cr, uid, [], context=context)
        i = 1
        for c in c_obj.browse(cr, uid, all_c, context=context):
            values = c_obj.get_value_from_formula(cr, uid, c.id, context=context)
            if values:
                khoang.append([values[0], values[1], values[2], 0, values[3], values[4]])
                i += 1 

        data_to_create = []
        
        study_results = user_obj.get_study_result(cr, uid, uid, context=context)
        
        for year in study_results['details'].keys():
            for semester in study_results['details'][year].keys():
                lines = study_results['details'][year][semester]
                for line in lines:
                    mark = line[7]
                    index = 0
                    for k in khoang:
                        ok = True
                        if k[4] == '[':
                            if not (k[1] <= mark): ok = False
                        else: 
                            if not (k[1] < mark): ok = False
                        if k[5] == ']':
                            if not (k[2] >= mark): ok = False
                        else:
                            if not (k[2] > mark): ok = False
                        
                        if ok:
                            khoang[index][3] += 1
                        else:
                            index += 1 
        ids = []
        for k in khoang:
            data = {'key': k[0], 'value': k[3]}
            id = self.create(cr, uid, data, context=context)
            ids.append(id)
        return ids
aas_result_distribution()

class aas_classification_student(osv.TransientModel):
    _name = 'aas.classification.student'
    _columns = {
        'key': fields.char('Xếp loại', size=64),
        'value': fields.integer('Số lượng'),
    }
    _defaults = {}
    def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
        sql = ''' DELETE FROM aas_classification_student '''
        cr.execute(sql)
        
        user_obj = self.pool.get('res.users')
        year_obj = self.pool.get('aas.academic.year')
        c_obj = self.pool.get('aas.classification')
        
        cur_stu = user_obj.browse(cr, uid, uid, context=context)
        students_ids = [uid]
        args = [('student', '=', True)]
        type = context.get('filter_key', 'school')
        if type == 'session':
            session_id = False
            if cur_stu.session_id.id:
                session_id = cur_stu.session_id.id
            args.append(('session_id', '=', session_id))
        elif type == 'dept':
            dept_id = False
            if cur_stu.dept_id.id:
                dept_id = cur_stu.dept_id.id
            args.append(('dept_id', '=', dept_id))
        elif type == 'class':
            class_id = False
            if cur_stu.class_id.id:
                class_id = cur_stu.class_id.id
            args.append(('class_id', '=', class_id))
            
        ids = user_obj.search(cr, uid, args, context=context)
        students_ids.extend(ids)
        students_ids = list(set(students_ids))

        khoang = []
        all_c = c_obj.search(cr, uid, [], context=context)
        i = 1
        for c in c_obj.browse(cr, uid, all_c, context=context):
            values = c_obj.get_value_from_formula(cr, uid, c.id, context=context)
            if values:
                khoang.append([values[0], values[1], values[2], 0, values[3], values[4]])
                i += 1 

        data_to_create = []
        
        students = user_obj.browse(cr, uid, students_ids, context=context)
        
        for student in students:
            gpa = student.gpa
            index = 0
            for k in khoang:
                ok = True
                if k[4] == '[':
                    if not (k[1] <= gpa): ok = False
                else: 
                    if not (k[1] < gpa): ok = False
                if k[5] == ']':
                    if not (k[2] >= gpa): ok = False
                else:
                    if not (k[2] > gpa): ok = False
                        
                if ok:
                    khoang[index][3] += 1
                else:
                    index += 1 
        ids = []
        for k in khoang:
            data = {'key': k[0], 'value': k[3]}
            id = self.create(cr, uid, data, context=context)
            ids.append(id)
        return ids
aas_classification_student()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
